using AutoMapper;
using MediatR;
using Newtonsoft.Json;
using ProduceBasicData.Api.Application.Command.ProductionManage.Technology;
using ProduceBasicData.Domain.Inventories;
using ProduceBasicData.Domain.ProductionManage;
using ProduceBasicData.ErrorCode;
using ProduceBasicData.Infrastructure.Interface;
using ProduceBasicData.Api.Services;
using ProduceBasicData.Api.DTO;
using System.Diagnostics;
using ProduceBasicData.Domain.FactoryModeling;

namespace ProduceBasicData.Api.Application.Handler.ProductionManage.Technology
{
    /// <summary>
    /// 工单生产任务处理器 - 中介者模式处理类
    /// </summary>
    public class ProcessWorkOrderCommandHandler : IRequestHandler<ProcessWorkOrderCommand, ApiResult<List<ProcessDto>>>
    {
        private readonly IBaseRespository<Production_report> _productionReportRepository;
        private readonly IBaseRespository<Work_order> _workOrderRepository;
        private readonly IBaseRespository<CraftModel> _craftRepository;
        private readonly IBaseRespository<ProcessModel> _processmodel;
        private readonly ICodeRuleService _codeRuleService;
        private readonly IMapper _mapper;

        public ProcessWorkOrderCommandHandler(
            IBaseRespository<Production_report> productionReportRepository,
            IBaseRespository<Work_order> workOrderRepository,
            IBaseRespository<CraftModel> craftRepository,
            ICodeRuleService codeRuleService,
            IMapper mapper,
            IBaseRespository<ProcessModel> processmodel)
        {
            _productionReportRepository = productionReportRepository;
            _workOrderRepository = workOrderRepository;
            _craftRepository = craftRepository;
            _codeRuleService = codeRuleService;
            _mapper = mapper;
            _processmodel = processmodel;
        }

        public async Task<ApiResult<List<ProcessDto>>> Handle(ProcessWorkOrderCommand request, CancellationToken cancellationToken)
        {
            var result = new ApiResult<List<ProcessDto>>
            {
                Code = ApiEnum.Success,
                Msg = "获取工序信息成功",
                Data = new List<ProcessDto>()
            };

            try
            {
                // 如果有PriviewJson，从JSON中解析工序信息
                if (!string.IsNullOrEmpty(request.PriviewJson))
                {
                    var processesFromJson = await ParseProcessesFromJson(request.PriviewJson);
                    result.Data.AddRange(processesFromJson);
                }

                // 如果没有从JSON获取到工序，或者需要补充完整的工序信息，从数据库查询
                if (result.Data.Count == 0)
                {
                    var processesFromDb = await GetProcessesFromDatabase();
                    result.Data.AddRange(processesFromDb);
                }
                else
                {
                    // 补充工序的完整信息（从数据库中根据processId或processCode查询）
                    await EnrichProcessInformation(result.Data);
                }

                result.Msg = $"成功获取 {result.Data.Count} 个工序信息";
            }
            catch (Newtonsoft.Json.JsonException ex)
            {
                result.Code = ApiEnum.Failed;
                result.Msg = $"JSON解析失败: {ex.Message}";
                result.Data = new List<ProcessDto>();
            }
            catch (Exception ex)
            {
                result.Code = ApiEnum.Failed;
                result.Msg = $"获取工序信息时发生错误: {ex.Message}";
                result.Data = new List<ProcessDto>();
            }

            return result;
        }

        /// <summary>
        /// 从JSON中解析工序信息
        /// </summary>
        /// <param name="priviewJson">工艺路线JSON字符串</param>
        /// <returns>工序DTO列表</returns>
        private async Task<List<ProcessDto>> ParseProcessesFromJson(string priviewJson)
        {
            var processes = new List<ProcessDto>();

            try
            {
                var craftNodeData = JsonConvert.DeserializeObject<CraftNode.Rootobject>(priviewJson);

                if (craftNodeData?.nodes != null)
                {
                    foreach (var node in craftNodeData.nodes)
                    {
                        if (node.properties != null)
                        {
                            var processDto = new ProcessDto
                            {
                                Id = node.properties.processId,
                                Processcode = node.properties.processCode,
                                Processname = !string.IsNullOrEmpty(node.properties.processName) 
                                    ? node.properties.processName 
                                    : node.text?.value,
                                Processdesc = node.properties.processDesc,
                                ProcessType = node.properties.processType,
                                // 这些字段需要从数据库补充或设置默认值
                                Reporting = "手动", // 默认值
                                CreateName = "系统",
                                CreateTime = DateTime.Now
                            };

                            processes.Add(processDto);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"解析JSON工序信息失败: {ex.Message}");
                throw;
            }

            return processes;
        }

        /// <summary>
        /// 从数据库获取工序信息
        /// </summary>
        /// <returns>工序DTO列表</returns>
        private async Task<List<ProcessDto>> GetProcessesFromDatabase()
        {
            var processes = new List<ProcessDto>();

            try
            {
                var processModels = await _processmodel.GetAllAsync();
                
                foreach (var model in processModels)
                {
                    var processDto = _mapper.Map<ProcessDto>(model);
                    processes.Add(processDto);
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"从数据库获取工序信息失败: {ex.Message}");
                throw;
            }

            return processes;
        }

        /// <summary>
        /// 补充工序的完整信息
        /// </summary>
        /// <param name="processes">工序DTO列表</param>
        private async Task EnrichProcessInformation(List<ProcessDto> processes)
        {
            try
            {
                var allProcessModels = await _processmodel.GetAllAsync();

                foreach (var processDto in processes)
                {
                    // 根据processId或processCode从数据库查找完整信息
                    var processModel = allProcessModels.FirstOrDefault(p => 
                        p.Id == processDto.Id || 
                        (!string.IsNullOrEmpty(processDto.Processcode) && p.Processcode == processDto.Processcode));

                    if (processModel != null)
                    {
                        // 用数据库中的完整信息补充DTO
                        processDto.Processcode = processModel.Processcode;
                        processDto.Processname = processModel.Processname;
                        processDto.Processdesc = processModel.Processdesc;
                        processDto.ProcessType = processModel.ProcessType;
                        processDto.Reporting = processModel.Reporting;
                        processDto.CreateName = processModel.CreateName;
                        processDto.CreateTime = processModel.CreateTime;
                        processDto.UpdateTime = processModel.UpdateTime;
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"补充工序信息失败: {ex.Message}");
                // 不抛出异常，继续返回已有的信息
            }
        }
    }
}
